package me.baicai.weixin.identity.repository;

import com.alibaba.fastjson.JSONObject;
import me.baicai.weixin.entity.gcb.Finance;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


public interface FinanceRepository extends JpaRepository<Finance, Long>
{

    @Query(value = "select remark, sum(amount) from finance where type = ?2 and DATE_FORMAT(createDate,'%Y-%m') = DATE_FORMAT(CURDATE(), ?1) GROUP BY remark", nativeQuery = true)
    List<JSONObject> findAllByCreateDate(String date, String type);

    @Query(value ="select souce from finance where type = ?2 and DATE_FORMAT(createDate,'%Y') = ?1 GROUP BY souce", nativeQuery = true)
    List<String> findTypeByYear(String yearIn, String in);

    @Query(value = "SELECT DATE_FORMAT(createDate,'%Y-%m') as time,sum(amount) as amount FROM finance where type = ?2 and souce = ?3 and DATE_FORMAT(createDate,'%Y') = ?1  GROUP BY  time ORDER BY time", nativeQuery = true)
    List<JSONObject> findAllByYearAndType(String yearIn, String in, String arr);

    @Query(value = "select i.amount - o.amount from (SELECT sum(amount) as amount FROM `finance` where type = 'in') as i , (SELECT sum(amount) as amount FROM `finance` where type = 'out') as o", nativeQuery = true)
    String findPool();

    List<Page> findAllByCreatedLike(String value, Pageable pageable);

    List<Page> findAllByType(String value, Pageable pageable);

    @Transactional
    void deleteAllByCreated(String created);
}
